# -*- coding: utf-8 -*-

from flask import Flask, request, url_for
from flask_socketio import SocketIO
from flask_socketio import send, emit
import threading
import subprocess
import time

app = Flask(__name__)
socketio = SocketIO(app)
g_Connect = 0
g_Open = False

@socketio.on("connect")
def connect(data):
    global g_Connect
    print("connect to client")
    g_Connect += 1
    if not g_Open:
        emit("test")

@socketio.on("disconnect")
def disconnect():
    global g_Connect
    print("disconnect to client")
    g_Connect -= 1

@socketio.on("test")
def test():
    global g_Open
    g_Open = True

def WithThread(obj):
    t = threading.Thread(target=obj)
    t.setDaemon(True)
    t.start()
    return t

def run():
    global g_Connect
    port_ = 5000
    @WithThread
    def thread():
        socketio.run(app, host="localhost", port=port_)
    @WithThread
    def thread():
        time.sleep(3)
        # if not g_Open:
        if g_Connect == 0:
            subprocess.run(f"C:/Program Files (x86)/Google/Chrome/Application/chrome.exe http://localhost:{port_}/static/examples/index.html")
    while not g_Open:
    # while g_Connect == 0:
        time.sleep(1)

def Send(*arg, **kwarg):
    kwarg["broadcast"] = True
    kwarg["namespace"] = "/"
    with app.test_request_context('/'):
        send(*arg, **kwarg)

def Emit(*arg, **kwarg):
    kwarg["broadcast"] = True
    kwarg["namespace"] = "/"
    with app.test_request_context('/'):
        emit(*arg, **kwarg)

def wait():
    while True:
        time.sleep(1000)

run()